// 将对象转为查询字符串
function qs(obj) {
  return Object.entries(obj)
    .reduce((r, el) => {
      r += `${el[0]}=${el[1]}&`;
      return r;
    }, "")
    .slice(0, -1);
}

export function ajax(obj) {
  if (!obj.method) {
    obj.method = "GET";
  }
  // 拼接查询参数
  if (obj.config.params) {
    obj.url += "?" + qs(obj.config.params);
  }

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(obj.method, obj.url);
    if (obj.config.timeout) {
      xhr.timeout = obj.config.timeout;
    }
    if (obj.config.ontimeout) {
      xhr.ontimeout = obj.config.ontimeout;
    }
    if (obj.config.onprogress) {
      xhr.onprogress = obj.config.onprogress;
    }
    // 设置header
    if (obj.config.headers) {
      Object.entries(obj.config.headers).forEach((el) => {
        xhr.setRequestHeader(el[0], el[1]);
      });
    }
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = function () {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(xhr.response);
      }
    };
    xhr.send(JSON.stringify(obj.data));
  });
}

export function post(...arg) {
  // 处理参数
  const obj = { method: "POST" };
  if (arg.length === 1) {
    obj.url = arg[0];
  }
  if (arg.length === 2) {
    obj.url = arg[0];
    obj.data = arg[1];
  }
  if (arg.length === 3) {
    obj.url = arg[0];
    obj.config = arg[1];
    obj.data = arg[2];
  }

  return ajax(obj);
}

export function put(...arg) {
  // 处理参数
  const obj = { method: "PUT" };
  if (arg.length === 1) {
    obj.url = arg[0];
  }
  if (arg.length === 2) {
    obj.url = arg[0];
    obj.data = arg[1];
  }
  if (arg.length === 3) {
    obj.url = arg[0];
    obj.config = arg[1];
    obj.data = arg[2];
  }
  return ajax(obj);
}

export function patch(...arg) {
  // 处理参数
  const obj = { method: "PATCH" };
  if (arg.length === 1) {
    obj.url = arg[0];
  }
  if (arg.length === 2) {
    obj.url = arg[0];
    obj.data = arg[1];
  }
  if (arg.length === 3) {
    obj.url = arg[0];
    obj.config = arg[1];
    obj.data = arg[2];
  }
  return ajax(obj);
}

function del(...arg) {
  // 处理参数
  const obj = { method: "DELETE" };
  if (arg.length === 1) {
    obj.url = arg[0];
  }
  if (arg.length === 2) {
    obj.url = arg[0];
    obj.config = arg[1];
  }
  return ajax(obj);
}

function get(...arg) {
  // 处理参数
  const obj = { method: "GET" };
  if (arg.length === 1) {
    obj.url = arg[0];
  }
  if (arg.length === 2) {
    obj.url = arg[0];
    obj.config = arg[1];
  }
  return ajax(obj);
}

export default {
  get,
  post,
  delete: del,
  put,
  patch,
};
